package com.itheima.service.imp;

import com.itheima.VO.OrderSettingVO;
import com.itheima.mapper.OrdersettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.OrdersettingService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersettingServiceImp implements OrdersettingService {

    @Autowired
    private OrdersettingMapper ordersettingMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private OrderService orderService;

    public void download(HttpServletResponse response,String filename){

        try {
            //在内存中创建一个Excel文件
            XSSFWorkbook excel = new XSSFWorkbook();
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.createSheet("Sheet1");
            //在Sheet中创建行对象,rownum编号从0开始
            XSSFRow row = sheet.createRow(0);
            //创建单元格并且写入文件内容
            row.createCell(0).setCellValue("可约预日期");
            row.createCell(1).setCellValue("可预约人数");

            //获取之后的三十天的日期
            List<String> riqi = getNextThirtyDays();
            //把三十天的日期写入Excel中
            for (int i = 0; i < riqi.size(); i++) {
                //创建一个新行
                row = sheet.createRow(i+1);
                row.createCell(0).setCellValue(riqi.get(i));
                row.createCell(1).setCellValue("100");
            }



            //通过输出流将内存中的Excel文件写入到磁盘
//            FileOutputStream out = new FileOutputStream(new File("bxg-health-backend\\src\\main\\resources/excel/ordersetting_template.xlsx"));
//            excel.write(out);

            //关闭资源
//            out.close();
//            excel.close();
            // 将生成的Excel文件输出到响应流中（假设你已经配置好了HttpServletResponse response）
             response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//             response.setHeader("Content-Disposition", "attachment; filename=ordersetting.xlsx");
             response.setHeader("Content-Disposition", "attachment; filename="+filename);
             excel.write(response.getOutputStream());
             excel.close();

        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 获取下30天的日期
     * @return
     */
    private List<String> getNextThirtyDays() {
        List<String> nextThirtyDays = new ArrayList<>();
        LocalDate today = LocalDate.now();
        for (int i = 0; i < 31; i++) {
            LocalDate date = today.plusDays(i+1);
            nextThirtyDays.add(date.toString());
        }
        return nextThirtyDays;
    }


    /**
     * 根据日期修改可预约人数
     * @param OrderSetting
     * @return
     */
    public int editNumberByOrderDate(OrderSetting OrderSetting) {
        OrderSetting.getOrderDate();
        return ordersettingMapper.editNumberByOrderDate(OrderSetting);

    }

    /**
     * 预约设置--根据年月查询预约信息
     * @param month
     * @return
     */
    public List<OrderSetting> getOrderSettingByMonth(String month){

        return ordersettingMapper.getOrdersSettingByMonth(month);
    }


    /**
     * 预约设置--批量导入
     * @param file
     * @return
     */
    @Transactional
    public int uploadFromExcel(MultipartFile file) {
        List<OrderSetting> orderSettings = new ArrayList<>();
        try (InputStream inputStream = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(inputStream)) {

            Sheet sheet = workbook.getSheetAt(0);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) continue; // 跳过表头

                String dateCell = row.getCell(0).getStringCellValue();
                String numberCell = row.getCell(1).getStringCellValue();

                int number  = Integer.parseInt(numberCell); // 直接将字符串转换为整数;

                OrderSetting orderSetting = new OrderSetting();
                // 将 LocalDate 转换为字符串
//                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                orderSetting.setOrderDate(dateCell);
                orderSetting.setNumber(number);

                orderSettings.add(orderSetting);
            }
            // 批量保存到数据库
            ordersettingMapper.saveAll(orderSettings);
//            for (OrderSetting orderSetting : orderSettings){
//                ordersettingMapper.saveAll(orderSetting);
//            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    //今日预约人数
    public Integer todayOrderNumber(LocalDate reportDate){
        Integer todayOrderNumber = ordersettingMapper.todayOrderNumber(reportDate);
        if (todayOrderNumber == null){
            todayOrderNumber = 0;
        }
        return todayOrderNumber;
    }

    //本周预约人数
    public Integer thisWeekOrderNumber(LocalDate reportDate){
        LocalDate startDate = reportDate.with(DayOfWeek.MONDAY);
        LocalDate endDate = reportDate.with(DayOfWeek.SUNDAY);
        Integer thisWeekOrderNumber = ordersettingMapper.thisWeekOrderNumber(startDate,endDate);
        if (thisWeekOrderNumber == null){
            thisWeekOrderNumber = 0;
        }
        return thisWeekOrderNumber;
    }

    //本月预约人数
    public Integer thisMonthOrderNumber(LocalDate reportDate){
        LocalDate startDate = reportDate.withDayOfMonth(1);
        LocalDate endDate = reportDate.withDayOfMonth(reportDate.lengthOfMonth());
        log.info("本月第一天：{}",startDate);
        log.info("本月最后一天：{}",endDate);
        Integer thisMonthOrderNumber = ordersettingMapper.thisMonthOrderNumber(startDate,endDate);
        if (thisMonthOrderNumber == null){
            thisMonthOrderNumber = 0;
        }
        return thisMonthOrderNumber;
    }

    //热门套餐
    public List<Map<String, Object>> getHotSetmeal(){
        List<Map<String, Object>> list = ordersettingMapper.getHotSetmeal();
        log.info("热门套餐：{}",list);
        Long setmealCounts = 0L; // 使用 Long 类型
        for (Map<String, Object> map : list){
            setmealCounts += (Long) map.get("setmeal_count"); // 强制转换为 Long
        }

        int size = list.size();
        for (int i = 0; i < size; i++) {
            Map<String, Object> map = list.get(i);
            Long setmeal_count = (Long) map.get("setmeal_count"); // 强制转换为 Long
            if (setmeal_count == null) {
                setmeal_count = 0L;
            }
            Double proportion = Double.parseDouble(String.format("%.4f", (double) setmeal_count / setmealCounts));
            map.put("proportion", proportion);
        }

        return list;
    }

    //导出运营数据报表
    public void exportBusinessData(HttpServletResponse response) {
        log.info("获取运营数据");
        LocalDate reportDate = LocalDate.now(); //日期

        //会员数据统计
        Integer todayNewMember = memberService.todayNewMember(reportDate);  //今日新增会员
        Integer thisWeekNewMember = memberService.thisWeekNewMember(reportDate); //本周新成员
        Integer thisMonthNewMember = memberService.thisMonthNewMember(reportDate); //本月新增会员
        Integer totalMember = memberService.totalMember(); //总会员
        //预约数据统计
        Integer todayVisitsNumber = orderService.todayVisitsNumber(reportDate);  //今日到诊数
        Integer thisWeekVisitsNumber = orderService.thisWeekVisitsNumber(reportDate); //本周到诊数
        Integer thisMonthVisitsNumber = orderService.thisMonthVisitsNumber(reportDate); //本月到诊数
        //到诊数据统计
        Integer todayOrderNumber = this.todayOrderNumber(reportDate); //今日预约数
        Integer thisWeekOrderNumber = this.thisWeekOrderNumber(reportDate); //本周预约数
        Integer thisMonthOrderNumber = this.thisMonthOrderNumber(reportDate);//本月预约数
        //热门套餐
        List<Map<String, Object>> hotSetmeal= this.getHotSetmeal();

        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/report_template.xlsx");
        try {
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(2).getCell(5).setCellValue(reportDate.toString());
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);

            if (hotSetmeal != null && !hotSetmeal.isEmpty()) {
                for (int i = 0, len = hotSetmeal.size(); i < len; i++) {
                    Map<String, Object> map = hotSetmeal.get(i);
                    if (map != null) {
                        XSSFRow row = sheet.getRow(13 + i);
                        if (row == null) {
                            row = sheet.createRow(13 + i);
                        }
                        XSSFCell nameCell = row.getCell(4);
                        if (nameCell == null) {
                            nameCell = row.createCell(4);
                        }
                        nameCell.setCellValue(map.get("name") != null ? map.get("name").toString() : "");

                        XSSFCell proportionCell = row.getCell(5);
                        if (proportionCell == null) {
                            proportionCell = row.createCell(5);
                        }
                        proportionCell.setCellValue(map.get("proportion") != null ? (Double) map.get("proportion") : 0.0);

                        XSSFCell countCell = row.getCell(6);
                        if (countCell == null) {
                            countCell = row.createCell(6);
                        }
                        countCell.setCellValue(map.get("setmeal_count") != null ? (Long) map.get("setmeal_count") : 0L);
                    }
                }
            }

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=report_template.xlsx");

            //通过输出流将文件下载到客户端浏览器中
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关闭资源
            out.flush();
            out.close();
            excel.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
